package com.qf.xiaomi.service.impl;

import com.qf.xiaomi.dao.CartDao;
import com.qf.xiaomi.dao.OrderDao;
import com.qf.xiaomi.dao.OrderDetailDao;
import com.qf.xiaomi.dao.impl.CartDaoImpl;
import com.qf.xiaomi.dao.impl.OrderDaoImpl;
import com.qf.xiaomi.dao.impl.OrderDetailDaoImpl;
import com.qf.xiaomi.pojo.Cart;
import com.qf.xiaomi.pojo.Order;
import com.qf.xiaomi.pojo.OrderDetail;
import com.qf.xiaomi.service.OrderService;
import com.qf.xiaomi.utils.RandomUtils;

import java.util.Date;
import java.util.List;

/**
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
public class OrderServiceImpl implements OrderService {

    CartDao cartDao = new CartDaoImpl();
    OrderDao orderDao = new OrderDaoImpl();
    OrderDetailDao orderDetailDao = new OrderDetailDaoImpl();


    /**
     * 提交订单
     *  1. 获取当前用户购物车数据
     *  2. 添加 order 订单表
     *  3. 添加 orderDetails 订单详情表
     *  4. 清空购物车
     * @param aid
     * @param uid
     */
    @Override
    public Order addOrder(Integer aid, int uid) {
        //当前用户购物车数据
        List<Cart> carts = cartDao.getCart(uid);
        double sum = 0;
        //计算订单的总额
        for (Cart cart : carts) {
            sum += cart.getMoney();
        }

        //添加订单
        Order order = new Order();
        //手动生成订单编号(唯一)
        String orderId = RandomUtils.createActive();

        order.setId(orderId);
        order.setStatus("1");
        order.setUid(uid);
        order.setAid(aid);
        order.setMoney(sum);
        order.setTime(new Date());

        orderDao.insert(order);

        //添加订单详情（一个购物车对象，对应一个订单详情）
        for (Cart cart : carts) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOid(orderId); //订单id
            orderDetail.setPid(cart.getPid()); //商品id
            orderDetail.setNum(cart.getNum()); //数量
            orderDetail.setMoney(cart.getMoney()); //价格


            orderDetailDao.insert(orderDetail);
        }


        //清空购物车
        cartDao.clearCart(uid);

        return order;
    }

    @Override
    public void updateOrderStatus(String orderId, String status) {
        orderDao.updateStatus(orderId, status);
    }

    @Override
    public List<Order> getOrderList(int uid) {
        return orderDao.getOrderList(uid);
    }
}
